//
//  ChangCity.m
//  BSS
//
//  Created by Juvi on 13-5-31.
//  Copyright (c) 2013年 juvid. All rights reserved.
//

#import "ChangCity.h"
#import "DetectionSystemVersion.h"
#import "NSDictionary+MutableDeepCopy.h"
#import "Common.h"
#import "UIColor+expanded.h"
@interface ChangCity ()

@end

@implementation ChangCity
@synthesize names;
@synthesize keys;
@synthesize table;
@synthesize allNames;
@synthesize isSearching;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self BackButton];
    self.allNames=[NSDictionary dictionaryWithContentsOfFile:[self GetAllCity]];
//    NSLog(@"%@",self.allNames);
    [self resetSearch];
    // Do any additional setup after loading the view from its nib.
}
-(void)BackButton{
    if ([[DetectionSystemVersion alloc]Version]) {
        self.edgesForExtendedLayout=UIRectEdgeNone;
    }
    self.navigationItem.titleView=[DetectionSystemVersion SetBarTitle:@"百事搜"];
    [self.navigationItem setHidesBackButton:YES];
    UIButton *btnBack=[[DetectionSystemVersion alloc]BackButton];
    [btnBack addTarget:self action:@selector(BackReturn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem=backItem;
    
}
#pragma mark 导航栏按钮事件
-(void)BackReturn:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(NSString *) GetAllCity{
    NSString *path=[[NSBundle mainBundle]pathForResource:@"city" ofType:@"plist"];
    return path;
}
- (void)resetSearch {
    self.names = [self.allNames mutableDeepCopy];
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
//    [keyArray addObject:UITableViewIndexSearch];
    
    [keyArray addObjectsFromArray:[[self.allNames allKeys] sortedArrayUsingSelector:@selector(compare:)]];
//    [keyArray addObjectsFromArray:[self.allNames allKeys]];
       self.keys = keyArray;
    [self.keys setObject:[self.keys objectAtIndex:self.keys.count-1] atIndexedSubscript:0];
    [self.keys removeObjectAtIndex:self.keys.count-1];
//    NSLog(@"你好%@",str);

}
- (void)handleSearchForTerm:(NSString *)searchTerm {
    NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
    [self resetSearch];
    for (NSString *key in self.keys) {
        NSMutableArray *array = [names valueForKey:key];
        NSMutableArray *toRemove = [[NSMutableArray alloc] init];
        for (NSString *name in array) {
            if ([name rangeOfString:searchTerm
                            options:NSCaseInsensitiveSearch].location == NSNotFound)
                [toRemove addObject:name];
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:key];
        
        [array removeObjectsInArray:toRemove];
    }
    [self.keys removeObjectsInArray:sectionsToRemove];
    [table reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return ([keys count] > 0) ? [keys count] : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if ([keys count] == 0)
        return 0;
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    return [nameSection count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//        cell.backgroundColor=[UIColor grayColor];
//        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text = [nameSection objectAtIndex:row];
    if ([[nameSection objectAtIndex:indexPath.row] hasPrefix:self.strCurrentCiy]) {
        cell.imageView.image=[UIImage imageNamed:@"leftChangCity"];
        cell.indentationWidth=0;
        cell.indentationLevel=1;
    }
    else{
        cell.indentationWidth=30;
        cell.indentationLevel=1;
        cell.imageView.image=nil;
    }
    cell.textLabel.font=[UIFont systemFontOfSize:16];
  
//    cell.textLabel.text=@"上海市";
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
    if ([keys count] == 0)
        return nil;
    NSString *key = [keys objectAtIndex:section];
    
    if (key == UITableViewIndexSearch)
        return nil;
    return key;
}
-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 28;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *result=[[UIView alloc]init];
    result.backgroundColor=[UIColor colorWithHexString:@"0xcbe7ff"];
    if ([keys count]>0) {
        UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 28)];
        lab.text=[keys objectAtIndex:section];
        lab.backgroundColor=[UIColor clearColor];
        lab.font=[UIFont systemFontOfSize:14];
        [result addSubview:lab];
    }
    
    return result;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (isSearching)
        return nil;
    return keys;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.searchBar resignFirstResponder];
//    self.searchBar.showsCancelButton=NO;
//     [self.searchBar setShowsCancelButton:NO animated:YES];
//    [self.txtSearch resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark Table View Delegate Methods
- (NSIndexPath *)tableView:(UITableView *)tableView
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    NSString *strSelect=[nameSection objectAtIndex:row];
    //        NSLog(@"%@",str);
    NSRange range;
    if ([strSelect hasSuffix:@"市"]) {
        range = [strSelect rangeOfString:@"市"];
    }
    else if([strSelect hasSuffix:@"自治区"]){
        range = [strSelect rangeOfString:@"自治区"];

    }
    else if([strSelect hasSuffix:@"自治县"]){
        range = [strSelect rangeOfString:@"自治县"];

    }
    else if([strSelect hasSuffix:@"自治州"]){
        range = [strSelect rangeOfString:@"自治州"];

    }
    else if([strSelect hasSuffix:@"地区"]){
        range = [strSelect rangeOfString:@"地区"];

    }
    else if([strSelect hasSuffix:@"特别行政区"]){
        range = [strSelect rangeOfString:@"特别行政区"];

    }
    strSelect=[strSelect substringToIndex:range.location];
    [Common SetCity:strSelect];
    [Common SetProvince:@""];
//    NSLog(@"%@",strSelect);
//    [self.txtSearch resignFirstResponder];
     [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
//    isSearching = NO;
//    self.txtSearch.text = @"";
//    [tableView reloadData];
    return indexPath;
}
- (NSInteger)tableView:(UITableView *)tableView
sectionForSectionIndexTitle:(NSString *)title
               atIndex:(NSInteger)index {
    NSString *key = [keys objectAtIndex:index];
    if (key == UITableViewIndexSearch) {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    } else return index;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    NSLog(@"%@  %@",self.txtSearch .text,string);
    if ([textField.text length] == 0) {
//        NSLog(@"空的");
        [self resetSearch];
        [table reloadData];
        return YES;
    }
    [self handleSearchForTerm:textField.text];
//     NSLog(@"不空的");
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
//    NSLog(@"完成");
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    isSearching = NO;
     [self resetSearch];
    [table reloadData];

    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    isSearching = YES;
    [table reloadData];
}
#pragma mark -
#pragma mark Search Bar Delegate Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
//    self.searchBar.showsCancelButton=NO;
//     [self.searchBar setShowsCancelButton:NO animated:YES];
    NSString *searchTerm = [searchBar text];
    [self handleSearchForTerm:searchTerm];
}

- (void)searchBar:(UISearchBar *)searchBar
    textDidChange:(NSString *)searchTerm {
    if ([searchTerm length] == 0) {
        isSearching = NO;
        [self resetSearch];
        [table reloadData];
        return;
    }
    [self handleSearchForTerm:searchTerm];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//    [self.searchBar setShowsCancelButton:NO animated:YES];
    
    isSearching = NO;
    self.searchBar.text = @"";
    [self resetSearch];
    [table reloadData];
    [searchBar resignFirstResponder];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
//    [self.searchBar setShowsCancelButton:YES animated:YES];
    
    isSearching = YES;
    [table reloadData];
}
@end
